package org.xxpay.pay.mq;

import com.alibaba.fastjson.JSONObject;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.AlipayCash;
import org.xxpay.core.entity.AlipayCashDetail;
import org.xxpay.core.entity.PayInterfaceTypeTemplate;
import org.xxpay.core.service.IXxPayAlipayCashService;
import org.xxpay.pay.channel.alipay.AlipayCampaignCashService;
import org.xxpay.pay.service.CommonService;

import javax.jms.*;
import java.util.List;

@Component
public class Mq4AlipayCash {

    @Autowired
    private Queue alipayCashQueue;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private CommonService commonService;

    @Autowired
    private AlipayCampaignCashService alipayCampaignCashService;

    @Autowired
    private IXxPayAlipayCashService xxPayAlipayCashService;


    private static final MyLog _log = MyLog.getLog(Mq4AlipayCash.class);

    public void send(String msg) {
        _log.info("发送MQ消息:msg={}", msg);
        this.jmsTemplate.convertAndSend(this.alipayCashQueue, msg);
    }

    /**
     * 发送延迟消息
     * @param msg
     * @param delay
     */
    public void send(String msg, long delay) {
        _log.info("发送MQ延时消息:msg={},delay={}", msg, delay);
        jmsTemplate.send(this.alipayCashQueue, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                TextMessage tm = session.createTextMessage(msg);
                tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
                tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 1*1000);
                tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 1);
                return tm;
            }
        });
    }

    @JmsListener(destination = MqConfig.ALIPAY_CASH_QUEUE_NAME)
    public void receive(String msg) {

        JSONObject jsonObject = JSONObject.parseObject(msg);
        Integer cashId = jsonObject.getInteger("cashId");

        AlipayCash dbRecord = commonService.alipayCashService.findById(cashId);

        //如果不是处理中状态， 无需处理
        if (dbRecord.getTaskStatus() != AlipayCash.TASK_STATUS_ING) {
            return ;
        }

        //查询账号模板
        PayInterfaceTypeTemplate accountTemplate = commonService.payInterfaceTypeTemplateService.findById(dbRecord.getAccountTemplateId());

        //查询全部 可用账户
        List<AlipayCashDetail> users = commonService.alipayCashDetailService.selectByCashId(cashId);
        for(AlipayCashDetail detail: users){
            try {

                AlipayCash newRecord = commonService.alipayCashService.findById(cashId); //查询最新状态
                if (newRecord.getTaskStatus() == AlipayCash.TASK_STATUS_CANCEL) {  //当任务状态发生改变(变为了已取消发放)， 不在触发领红包
                    _log.error("用户取消发放！cashId=", cashId);
                    return ;
                }

                AlipayCashDetail updateRecord = new AlipayCashDetail();
                updateRecord.setId(detail.getId());

                JSONObject apiResult = alipayCampaignCashService.trigger(accountTemplate.getParamTemplate(), dbRecord.getAlipayCrowdNo(), detail);
                boolean isSuccess = apiResult.getBooleanValue("isSuccess");
                if(isSuccess){
                    updateRecord.setStatus(AlipayCashDetail.STATUS_SUCCESS); //分账成功
                    updateRecord.setRealAmount(apiResult.getLong("prizeAmount")); //支付宝返回的金额字段
                }else{

                    updateRecord.setStatus(AlipayCashDetail.STATUS_FAIL); //分账失败
                    updateRecord.setRealAmount(0L); //
                    updateRecord.setAlipayErrorMsg(apiResult.getString("errMsg")); //如分账失败，记录支付宝返回的信息
                }

                // 更新明细 &  更新用户表的分账总金额，如果超限更新状态
                commonService.alipayCashDetailService.updateDetailAndUser(updateRecord, cashId, detail.getCashUserId());

                // Thread.sleep(1000); //休眠时间： 1秒   ：20190701实时发放

            } catch (Exception e) {
                _log.error("用户触发红包失败，alipayCashUserId={}" + detail.getCashUserId(), e);
            }
        }

        //更新红包记录为 [任务完成]
        AlipayCash updateRecord = new AlipayCash();
        updateRecord.setId(cashId); updateRecord.setTaskStatus(AlipayCash.TASK_STATUS_FINISH);
        commonService.alipayCashService.update(updateRecord);

        xxPayAlipayCashService.updateInfoFromAlipay(cashId); //查询支付宝最新状态 并更新

    }
}
